﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Runtime.Serialization;

namespace SMARTMobile.WinPhone
{
    /// <summary>
    /// This class provides all that is needed to automatically update
    /// the UI as items are added or removed from the collection
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ObviousCollection<T> : ObservableCollection<T>
    {
        /// <summary>
        /// 
        /// </summary>
        public bool IsDirty { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public event EventHandler<PropertyChangedEventArgs> OnCollectionDirty;

        /// <summary>
        /// 
        /// </summary>
        public ObviousCollection()
        {   
            CollectionChanged += ThisCollectionChanged;
        }

         /// <summary>
        /// 
        /// </summary>
        public ObviousCollection(IEnumerable<T> items) : this()
        {
            AddRange(items);
        }

        public void AddRange(IEnumerable<T> items)
        {
            if (null == items) return;
            foreach (var item in items) Add(item);
        }

        private void ThisCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            IsDirty = true;
        }

        private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            IsDirty = true;
            if (null != OnCollectionDirty) OnCollectionDirty(sender, e);
        }

        protected override void InsertItem(int index, T item)
        {
            var p = item as INotifyPropertyChanged;
            if (p != null) p.PropertyChanged += OnPropertyChanged;
            base.InsertItem(index, item);
        }

        protected override void RemoveItem(int index)
        {
            var p = this[index] as INotifyPropertyChanged;
            if (p != null) p.PropertyChanged -= OnPropertyChanged;
            base.RemoveItem(index);
        }
    }
}